package com.sk.ccflower.server.common.tcpManager;

import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.log4j.Logger;

import com.sk.ccflower.lib.define.BaseCfg;
import com.sk.ccflower.server.lib.sysUtils.BaseMain;

public class TcpManager extends BaseMain {
	
	protected TcpManagerServer m_ss = null;
	protected ConcurrentHashMap<String, TcpManagerSession> m_hashClient;
	
	public TcpManager() throws Exception {
		super();
		
		m_hashClient = new ConcurrentHashMap<String, TcpManagerSession>();
	}
	
	public void init() throws Exception {
		TcpManagerStatusThread statusThrd = new TcpManagerStatusThread( this );
		statusThrd.start();
		
		TcpManagerClientQueueThread cliQueueThread = new TcpManagerClientQueueThread( this );
		cliQueueThread.start();
	}
	
	public void run() {
		try {
			m_ss = new TcpManagerServer(BaseCfg.TCPIP_PORT, TcpManagerSession.class);
			m_ss.run();
		} catch (Exception e) {
			m_log.fatal("run error: ", e);
		} finally {
			if (m_ss != null)
				m_ss.close();
		}
	}
	
	public static void main(String[] args) {
		try {
			TcpManager main = new TcpManager();
			main.init();
			main.run();
		} catch (Exception e) {
			System.out.println( e.toString() );
		} finally {
			
		}
	}
	
}


class TcpManagerStatusThread extends Thread {
	
	TcpManager m_parent;
	protected Logger m_log;
	
	public TcpManagerStatusThread( TcpManager _parent ) {
		this.m_parent = _parent;
		this.m_log = Logger.getLogger( getClass() );
		m_log.debug( "TcpManagerStatusThread Constructor called!" );
	}
	
	public void run() {
		Iterator<String> itr = null;
		String email = null;
		TcpManagerSession sess = null;
		while ( true ) {
			itr = m_parent.m_hashClient.keySet().iterator();
			
			m_log.debug( "=====================================================" );
			while ( itr.hasNext() ) {
				email = (String) itr.next();
				sess = (TcpManagerSession) m_parent.m_hashClient.get(email);
				
				if ( null == sess ) {
					m_parent.m_hashClient.remove( email );
					continue;
				}
				if ( null == sess.getSockChannel() ) {
					m_parent.m_hashClient.remove( email );
					continue;
				}
				if ( false == sess.getSockChannel().isConnected() ) {
					m_parent.m_hashClient.remove( email );
					continue;
				}
				
				m_log.debug( "### Email : "+email );
				m_log.debug( "### Session : "+sess.getSockChannel().socket().getInetAddress().getHostAddress()+":"+sess.getSockChannel().socket().getPort() );
			}
			m_log.debug( "### Total Clients : "+m_parent.m_hashClient.size() );
			m_log.debug( "=====================================================" );
			
			try {
				Thread.sleep( (60*1000) );
			} catch (InterruptedException e) {
				m_log.error( e );
				e.printStackTrace();
			}
		}
	}
	
}
